package com.yuoj.yuojbackendserviceclient.service;

import com.yuoj.backendcommon.common.ErrorCode;
import com.yuoj.backendcommon.entity.User;
import com.yuoj.backendcommon.enums.UserRoleEnum;
import com.yuoj.backendcommon.exception.BusinessException;
import com.yuoj.backendcommon.utils.CopyUtil;
import com.yuoj.backendcommon.vo.UserVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.Collection;
import java.util.List;

import static com.yuoj.backendcommon.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务
 *

 */
@FeignClient(name = "yuoj-backend-user-service",path = "/api/user/inner")
public interface UserFeignClient  {


    /**
     * 根据id获取用户
     * @param id
      */
    @GetMapping("/get/id")
    User getById(@RequestParam("id") long id);

    /**
     * 根根据id获取用户集合
     * @param idList
     * @return
     */
    @GetMapping("/get/ids")
    List<User> listByIds (@RequestParam("idList") Collection<Long> idList);


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    default User getLoginUser(HttpServletRequest request){
        HttpSession session = request.getSession ();
        User user = (User) session.getAttribute (USER_LOGIN_STATE);
        //判断是否登录
        if (user==null){
            throw new BusinessException (ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }


    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
   default boolean isAdmin(User user){
       return user!=null && UserRoleEnum.ADMIN.getValue ().equals (user.getUserRole ());
   }


    /**
     * 获取脱敏的用户信息
     *
     * @param user
     * @return
     */
   default UserVO getUserVO(User user){
       if (user==null){
           return null;
       }
       return CopyUtil.copy (user, UserVO.class);

   }



}
